package GoodsService

import (
	"context"
	"gdshop-back-end-go/common/request/BaseReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/response/GoodsResp"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"sort"
	"time"
)

func SetActivityOption(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()

	activityId := r.GetInt64("activity_id")
	if activityId == 0 {
		return response.FailByRequestMessage(r, "活动id不能为空")
	}
	var postData []*GoodsResp.GoodsActivityOption
	if err := gconv.Structs(r.GetString("data", ""), &postData); err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	// 判断是否有数据
	if len(postData) == 0 {
		return response.FailByRequestMessage(r, "没有数据")
	}
	// 判断价格不能小于1
	for _, item := range postData {
		if item.GaglPrice < 1 {
			return response.FailByRequestMessage(r, item.Title+",价格不能小于1分钱")
		}
		// 判断自定义库存不能小于1
		if item.CustomStock == 2 && item.GaglStock < 1 {
			return response.FailByRequestMessage(r, item.Title+",自定义库存不能小于1")
		}
	}
	// 升序
	sort.Slice(postData, func(i, j int) bool {
		return postData[i].GaglPrice < postData[j].GaglPrice
	})
	miniPriceOptionId := postData[0].OptionId
	goodsId := postData[0].GoodsId
	// 找出需要插入的新数据
	var insertData []*GoodsResp.GoodsActivityOption
	for _, item := range postData {
		if item.GaglId == 0 {
			insertData = append(insertData, item)
		}
	}

	err := g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		// 删除旧数据
		_, err := tx.Model("goods_activity_goods_list").Where("goods_id", goodsId).
			Where("activity_id", activityId).Update(g.Map{
			"delete_at": time.Now().Unix(),
		})
		if err != nil {
			return err
		}
		var isMiniPrice bool = false
		// 插入新数据
		if len(insertData) > 0 {
			for _, insertDatum := range insertData {

				isMiniPrice = insertDatum.OptionId == miniPriceOptionId

				_, err := tx.Model("goods_activity_goods_list").Data(g.Map{
					"activity_id":     insertDatum.ActivityId,
					"goods_id":        insertDatum.GoodsId,
					"goods_option_id": insertDatum.OptionId,
					"price":           insertDatum.GaglPrice,
					"stock":           insertDatum.GaglStock,
					"custom_stock":    insertDatum.CustomStock,
					"is_mini_price":   isMiniPrice,
				}).InsertAndGetId()
				if err != nil {
					return err
				}
			}
		}
		// 更新数据
		for _, item := range postData {
			if item.GaglId > 0 {

				isMiniPrice = item.OptionId == miniPriceOptionId

				_, err := tx.Model("goods_activity_goods_list").Data(g.Map{
					"price":         item.GaglPrice,
					"stock":         item.GaglStock,
					"custom_stock":  item.CustomStock,
					"is_mini_price": isMiniPrice,
					"delete_at":     0,
				}).Where("id", item.GaglId).Update()
				if err != nil {
					return err
				}
			}
		}

		return nil
	})
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	return response.SuccessByRequestMessage(r, "成功")
}
